package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vos.NewsAuthVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.beanutils.BeanHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author azl
 * @since 2025-04-06
 */
@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    private final WmNewsMaterialMapper wmNewsMaterialMapper;

    private final WmMaterialMapper wmMaterialMapper;

    private final RabbitTemplate rabbitTemplate;

    private final WmNewsAutoScanService wmNewsAutoScanService;

    private final KafkaTemplate<String,Object> kafkaTemplate;

    private final WmUserMapper wmUserMapper;

    private final WmChannelMapper wmChannelMapper;

    private final IArticleClient articleClient;



    /**
     * 文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {

        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getBeginPubDate() != null) {
            lambdaQueryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            lambdaQueryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
        page = page(page, lambdaQueryWrapper);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    /**
     * 提交或保存文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //0.条件判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //属性拷贝 属性名词和类型相同才能拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片  list---> string
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //如果当前封面类型为自动 -1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);

        //2.判断是否为草稿  如果为草稿结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            log.info("存入草稿成功！");
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials = extractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials,wmNews.getId());

        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,materials);

        //审核文章
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        if(dto.getPublishTime().getTime()<=System.currentTimeMillis()){
            rabbitTemplate.convertAndSend("ReviewArticle.direct","ReviewArticle",wmNews.getId());
        }else{
            Integer time = (int) (wmNews.getPublishTime().getTime() - System.currentTimeMillis());
            rabbitTemplate.convertAndSend("ReviewArticleDelay.direct",
                    "ReviewArticleDelay",
                    wmNews.getId(),
                    message -> {message.getMessageProperties().setDelay(time);
                                return message;}
            );
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable())
                    .eq(WmNews::getId,wmNews.getId()));
            log.info("修改文章成功！文章id:{}，修改文章配置enable:{}",wmNews.getId(),dto.getEnable());
        }

        //发送消息，通知article端修改文章配置
        if(wmNews.getArticleId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            log.info("生产者发送消息成功！");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     *
     * 第二个功能：保存封面图片与素材的关系
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();

        //如果当前封面类型为自动，则设置封面类型的数据
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //多图
            if(materials.size() >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if(materials.size() >= 1 && materials.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if(images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);
        }
        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }


    /**
     * 获取到文章内容中的图片信息
     * @param content
     * @return
     */
    private List<String> extractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSONArray.parseArray(content, Map.class);

        for (Map map : maps) {
           if (map.get("type").equals("image")){
               String imageUrl = (String) map.get("value");
               materials.add(imageUrl);
           }
        }
        return materials;
    }

    /**
     * 保存文章内容图片与素材的关系
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param wmContentReference
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short wmContentReference) {
        if(materials!=null&&!materials.isEmpty()){
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            if(wmMaterials==null||wmMaterials.size()==0){
                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
            }
            if(wmMaterials.size()!=materials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
            }
        /*List<Integer> ids = new ArrayList<>();
        for (WmMaterial wmMaterial : wmMaterials) {
            Integer id = wmMaterial.getId();
            ids.add(id);
        }*/
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelations(ids,newsId,wmContentReference);
        }
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架

        if (wmNews.getId() == null) {
            //保存
            save(wmNews);
        } else {
            //修改
            //删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }


    /**
     * 管理员查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult one_vo(Integer id) {

        WmNews wmNews = baseMapper.selectById(id);
        NewsAuthVo newsAuthVo = new NewsAuthVo();
        BeanUtils.copyProperties(wmNews,newsAuthVo);
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        newsAuthVo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(newsAuthVo);
    }

    /**
     * 审核失败
     * @param dto
     * @return
     */
    @Override
    public ResponseResult auth_fail(NewsAuthDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        lambdaUpdate().set(WmNews::getStatus,WmNews.Status.FAIL.getCode())
                .set(WmNews::getReason,dto.getMsg())
                .eq(WmNews::getId,dto.getId())
                .update();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 管理员查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listVo(NewsAuthDto dto) {
        dto.checkParam();
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery().orderByDesc(WmNews::getCreatedTime);

        //状态条件
        if(dto.getStatus()!=null){
            wrapper=wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //标题模糊查询
        if(StringUtils.isNotBlank(dto.getTitle())&&!dto.getTitle().equals("")){
            wrapper = wrapper.like(WmNews::getTitle, dto.getTitle());
        }
        IPage page = new Page(dto.getPage(), dto.getSize());
        page = page(page, wrapper);

        List<WmNews> wmNewsList = page.getRecords();

        List<NewsAuthVo> vos = new ArrayList<>();
        for (WmNews wmNews : wmNewsList) {
            NewsAuthVo vo = new NewsAuthVo();
            BeanUtils.copyProperties(wmNews, vo);
            if(wmNews.getUserId()!=null){
                WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
                if(wmUser!=null){
                    vo.setAuthorName(wmUser.getName());
                    vos.add(vo);
                }
            }
        }

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(vos);
        return responseResult;


    }

    /**
     * 审核通过
     * @param dto
     * @return
     */
    @Override
    public ResponseResult auth_pass(NewsAuthDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = baseMapper.selectById(dto.getId());

        //审核成功，保存app端的相关文章数据
        ResponseResult responseResult =saveAppArticle(wmNews);

        if (!responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsServiceImpl-管理员文章审核：保存app端的相关文章数据失败");
        }

        //回填article的id
        wmNews.setArticleId((Long) responseResult.getData());

        //修改状态
        wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
        if(dto.getMsg()!=null&&StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        baseMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 保存app端的相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();

        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);

        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());

        return articleClient.saveArticle(dto);
    }
}














